package aspct;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import service.ForbiddentService;

import java.lang.reflect.Field;

/**
 * @Author:Cjj
 * @Date:2025/5/11
 * 反射
 */
@Aspect
@Component
public class AllowWordAspect {
    @Autowired
    private ForbiddentService forbiddentService;

    @Pointcut("@annotation(com.record.annotation.AllowWord)")
    public void allowWordPointCut(){

    }

    //1.方法执行前  2.方法执行后 3.环绕通知
    @Before("allowWordPointcut()")
    public void checkAllowWord(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
               checkAllowWord((JoinPoint) arg);
        }
    }
    
    private void checkForbiddenWord(Object entity){
        if(entity ==null){
            return;
        }

        Field[] fields = entity.getClass().getDeclaredFields();
        for (Field field : fields) {
            if(field.getType().equals(String.class)){
                field.setAccessible(true);//给权限去访问
                try{
                     String value= (String) field.get(entity);
                     System.out.println("当前被校验的参数为:"+value);
                     if(!StringUtils.isEmpty(value)){
                          if(forbiddentService.isForbidden(value)){
                              throw new RuntimeException("存在违禁词");
                          }
                     }
                } catch (IllegalAccessException e) {
                   System.out.println("出现异常："+e.getMessage());
                }
            }
        }
    }
}

